#include "stdafx.h"

AccountManager::AccountManager()
{
	m_MapAccount.clear();
}

AccountManager::~AccountManager()
{

}

AccountManager* AccountManager::instance()
{
	static AccountManager inst;
	return &inst;
}

void AccountManager::loadData()
{
	string s;
	CReaderStream data;
	Global::Get_Value(AccountManagerKey, s);
	memcpy(data.c_str(), s.c_str(), (size_t)s.length());
	if (s.length() <= 0)
		return;
	data.parseBuf(s.c_str(), (SIZE_ST)s.length());
	DBVersion::DataHead head;
	data >> head.nVersion;
	data >> head.size;
	if (head.size != s.length())
	{
		assert(false);
		return;
	}
	int cout = 0;
	data >> cout;
	for (int i = 0; i < cout; i++)
	{
		Account account;
		const char* name = NULL;
		const char* password = NULL;
		data >> name;
		data >> password;
		strcpy(account.userName, name);
		strcpy(account.password, password);
		m_MapAccount.insert(std::make_pair(account.userName, account));
	}
}

void AccountManager::saveData()
{
	CWriterStream data;
	DBVersion::DataHead head;
	head.nVersion = DBVersion::AccountVersion_Cur;
	data << head.nVersion;
	head.size = 0;
	int pos = data.wpos();
	data << head.size;
	int count = (int)m_MapAccount.size();
	data << count;
	for (MapAccount::iterator it = m_MapAccount.begin(); it != m_MapAccount.end(); it++)
	{
		data << it->second.userName;
		data << it->second.password;
	}

	head.size = data.length();
	memcpy(data.c_str() + pos, &head.size, sizeof(int));
	Global::Put_Value(AccountManagerKey, data);

}
